package pcp

import (
	"bytes"
	"compress/zlib"
	"io"
)

// MustZlib zlib压缩数据
func MustZlib(src []byte) (dist []byte) {
	dist, _ = Zlib(src)
	return
}

// Zlib zlib压缩数据
func Zlib(src []byte) (dist []byte, err error) {
	var buf bytes.Buffer

	writer := zlib.NewWriter(&buf)
	defer writer.Close()

	_, err = writer.Write(src)
	if err != nil {
		return
	}

	err = writer.Flush()
	if err != nil {
		return
	}

	dist = buf.Bytes()

	return
}

// MustUnZlib 数据解压缩
func MustUnZlib(src []byte) (dist []byte) {
	dist, _ = UnZlib(src)
	return
}

// UnZlib 数据解压缩
func UnZlib(src []byte) (dist []byte, err error) {
	reader, err := zlib.NewReader(bytes.NewBuffer(src))
	if err != nil {
		return
	}
	defer reader.Close()

	return io.ReadAll(reader)
}
